package com.hankol.material

import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.activity.BaseActivity
import com.baselibrary.db.DBManager
import com.baselibrary.manager.FlowLayoutManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.view.SpaceItemDecoration
import com.hankol.material.adapter.SearchHistoryAdapter
import com.hankol.material.api.MaterialConstants
import com.hankol.material.bean.MaterialBusinessBean
import com.hankol.material.databinding.ActivityMaterialSearchBinding
import com.hankol.material.fragment.MaterialControlContentFragment
import com.hankol.material.viewmodel.MaterialBaseViewModel
import com.hankol.material.viewmodel.MaterialSearchViewModel
import com.xinlan.imageeditlibrary.editimage.utils.InputTools

/**新版素材库【搜索】
 * @author: merbng
 * @time: 2021/10/15 10:02
 * @description:
 */
@Route(path = ActivityRouter.MATERIAL.SEARCH)
class MaterialSearchActivity : BaseActivity() {
    private lateinit var viewModel: MaterialSearchViewModel
    private lateinit var binding: ActivityMaterialSearchBinding
    private var contentFragment: MaterialControlContentFragment? = null
    //搜索历史
    val searchHistoryAdapter: SearchHistoryAdapter by lazy { SearchHistoryAdapter() }

    val userIds: Int by lazy { SpUtils.getInstance().userId }

    override fun getLayoutId(): Int {
        return R.layout.activity_material_search
    }

    override fun init() {
        StatusBarUtil.setTranslucentStatus(this)
        binding = getDataBinding()
        viewModel = getActivityViewModelProvider(this).get(MaterialSearchViewModel::class.java)
        binding.backImageView.setOnClickListener { finish() }
        binding.rvHistory.layoutManager = FlowLayoutManager()
        binding.rvHistory.addItemDecoration(SpaceItemDecoration(CommonUtil.dip2px(this, 10f)))
        binding.rvHistory.adapter = searchHistoryAdapter
        //获取搜索历史
        getSearchHistory()
        binding.etSearch.postDelayed(Runnable {
            if (searchHistoryAdapter.data.size > 0) return@Runnable
            InputTools.showInput(binding.etSearch)
        }, 300)
        //点击 搜索历史
        searchHistoryAdapter.setOnItemClickListener { adapter, view, position ->
            binding.etSearch.setText("${searchHistoryAdapter.data[position]}")
            binding.etSearch.setSelection("${searchHistoryAdapter.data[position]}".length);
            searchContent()
        }
        binding.tvSearch.setOnClickListener {
            searchContent()
        }
        //清空
        binding.tvClear.setOnClickListener {
            DBManager.getInstance().deleteSearchHistory4Material(userIds)
            searchHistoryAdapter.setNewData(null)
            binding.rlHistorySearch.visibility = View.GONE
            binding.container.visibility = View.VISIBLE
            HKToastUtils.showToast("清空已完成")
        }
        //清空搜索内容
        binding.imgClear.setOnClickListener {
            binding.etSearch.setText(null)
        }
        binding.etSearch.requestFocus()
        binding.etSearch.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (count == 0) {
                    getSearchHistory()
                    binding.imgClear.visibility = View.GONE
                } else {
                    binding.imgClear.visibility = View.VISIBLE
                }
            }
        })
        binding.etSearch.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    searchContent()
                    return true
                }
                return false
            }
        });

        viewModel.onMaterialLoadCompleteListener = object : MaterialBaseViewModel.OnMaterialLoadCompleteListener {
            override fun onMaterialLoadComplete() {
                binding.container.visibility = View.VISIBLE
            }

        }

    }

    /**获取搜索历史
     * @author: merbng
     * @time: 2021/10/18 14:32
     * @description:
     */
    private fun getSearchHistory() {
        val searchHistoryList = DBManager.getInstance().querySearchHistory4Material(userIds)
        searchHistoryAdapter.setNewData(if (searchHistoryList.size > 12) searchHistoryList.subList(0, 12) else searchHistoryList)
        binding.rlHistorySearch.visibility = if (searchHistoryList.size == 0) View.GONE else View.VISIBLE
        binding.container.visibility = if (searchHistoryList.size == 0) View.VISIBLE else View.GONE
    }

    /**点击搜索
     * @author: merbng
     * @time: 2021/10/18 11:11
     * @description:
     */
    private fun searchContent() {
        val contentStr = binding.etSearch.text.toString().trim()
        if (TextUtils.isEmpty(contentStr)) {
            HKToastUtils.showToast("请输入搜索内容")
            return
        }
        //收起键盘
        hideSoftKeyboard()
        binding.rlHistorySearch.visibility = View.GONE
        //存一下本地
        DBManager.getInstance().insertSearchContent4Material(userIds, contentStr)
        if (contentFragment == null) {
            contentFragment = MaterialControlContentFragment.newInstance(MaterialBusinessBean(MaterialConstants.BUSINESS_TYPE_SEARCH, contentStr, 0, 0L, 0), null,false,this)
            contentFragment!!.onMaterialLoadCompleteListener = viewModel.onMaterialLoadCompleteListener
            val manager = supportFragmentManager
            val transaction = manager.beginTransaction()
            transaction.replace(R.id.container, contentFragment!!)
            transaction.commit()
        } else {
            contentFragment?.handlerData(MaterialBusinessBean(MaterialConstants.BUSINESS_TYPE_SEARCH, contentStr, 0, 0L, 0))
        }
    }
}